package com.heima.schedule.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.SceduleConstants;
import com.heima.common.constants.WeMediaConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2023/2/5 11:03
 * @Version 1.0
 */
@Service
@Slf4j
public class TaskServiceImpl implements ITaskService{

    @Autowired
    private TaskinfoMapper taskinfoMapper;
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    public final static int DEFAULT_VERSION = 1;
    @Autowired
    private CacheService cacheService;

    @Override
    public Long addTask(Task task) {
        //存数据库
        addToDb(task);
        //存redis
        saveToRedis(task);

        return task.getTaskId();
    }

    @Override
    public boolean cancelTask(Long taskId) {
        //取消任务逻辑：删除taskInfo  修改taskInfologs 删除redis
        Task task = updateDb(taskId,SceduleConstants.STATUS_CANCELLED);
        String key = task.getTaskType() + "-" + task.getPriority();
        if(task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lRemove(SceduleConstants.KEY_PRFIX_LIST + key, 0, JSON.toJSONString(task));
        }else {
            cacheService.zRemove(SceduleConstants.KEY_PRFIX_ZSET + key, JSON.toJSONString(task));
        }
        return true;
    }

    @Override
    public Task poll(Integer taskType, Integer priority) {
        String key = SceduleConstants.KEY_PRFIX_LIST + taskType + "-" + priority;
        String result = cacheService.lRightPop(key);
        if(StringUtils.isEmpty(result)){
            return null;
        }
        Task task = JSON.parseObject(result,Task.class);
        //更新数据库
        updateDb(task.getTaskId(), SceduleConstants.STATUS_EXECUTED);

        return task;
    }

    /**
     *
     * 修改任务
     * @param taskId
     * @param status
     * @return
     */
    private Task updateDb(Long taskId,Integer status){
        taskinfoMapper.deleteById(taskId);
        TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
        taskinfoLogs.setStatus(status);
        taskinfoLogsMapper.updateById(taskinfoLogs);

        Task task = new Task();
        BeanUtils.copyProperties(taskinfoLogs,task);
        task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        return task;
    }

    /**
     * 保存到redis
     * 执行时间<=当前时间  存list
     * 执行时间 > 当前时间 且小于 未来5分钟时间 存zset
     *
     * @param task
     */
    private void saveToRedis(Task task){

        String keyPostfix = task.getTaskType() + "-" + task.getPriority();

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);

        //马上执行的
        if(task.getExecuteTime() <= System.currentTimeMillis()){
            cacheService.lLeftPush(SceduleConstants.KEY_PRFIX_LIST + keyPostfix, JSON.toJSONString(task));
        }else if(task.getExecuteTime() <= calendar.getTime().getTime()){
            cacheService.zAdd(SceduleConstants.KEY_PRFIX_ZSET + keyPostfix,JSON.toJSONString(task),task.getExecuteTime());
        }

    }

    /**
     *
     * 保存数据库
     * @param task
     */
    private void addToDb(Task task){
        Taskinfo taskinfo = new Taskinfo();
        BeanUtils.copyProperties(task,taskinfo);
        taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
        taskinfoMapper.insert(taskinfo);

        TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
        BeanUtils.copyProperties(taskinfo,taskinfoLogs);
        taskinfoLogs.setVersion(DEFAULT_VERSION);
        taskinfoLogs.setStatus(SceduleConstants.STATUS_INIT);
        taskinfoLogsMapper.insert(taskinfoLogs);

        task.setTaskId(taskinfo.getTaskId());
    }

    @Scheduled(cron = "0 */50 * * * ?")
    public void refresh(){
        log.info("开始执行zset刷新到list任务");
        String LOCK_KEY = "REFRESH-LOCK-KEY";
        String result = cacheService.tryLock(LOCK_KEY, 10);
        if(StringUtils.isEmpty(result)){
            log.info("未获取到锁，不执行");
            return;
        }
        Set<String> keys = cacheService.scan(SceduleConstants.KEY_PRFIX_ZSET + "*");
        log.info("获取到keys:{}",keys);
        for(String key : keys){
            //key : zset-100-1
            String listKey = SceduleConstants.KEY_PRFIX_LIST + key.split(SceduleConstants.KEY_PRFIX_ZSET)[1];
            Set<String> tasks = cacheService.zRangeByScore(key, 0, System.currentTimeMillis());
            if(CollectionUtils.isEmpty(tasks)){
                log.info("当前{}没有要执行的数据",key);
                continue;
            }
            cacheService.refreshWithPipeline(key,listKey,tasks);
        }
        log.info("结束-执行zset刷新到list任务");
    }

    @Scheduled(cron = "0 */40 * * * ?")
    public void loadDataToZset(){
        log.info("数据库数据载入zset");
        String LOCK_KEY = "LOADDATA-LOCK-KEY";
        String result = cacheService.tryLock(LOCK_KEY, 10);
        if(StringUtils.isEmpty(result)){
            log.info("未获取到锁，不执行");
            return;
        }

        //删除zset和list中数据
        removeCache();

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);

        List<Taskinfo> taskinfos = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar.getTime()));
        if(CollectionUtils.isEmpty(taskinfos)){
            log.info("没有需要载入到zset中的数据");
            return;
        }
        for(Taskinfo taskinfo : taskinfos){
            Task task = new Task();
            BeanUtils.copyProperties(taskinfo,task);
            task.setExecuteTime(taskinfo.getExecuteTime().getTime());
            saveToRedis(task);
            log.info("Task载入zset--->{}",task);
        }
    }

    private void removeCache(){
        Set<String> listKey = cacheService.scan(SceduleConstants.KEY_PRFIX_LIST + "*");
        Set<String> zsetKey = cacheService.scan(SceduleConstants.KEY_PRFIX_ZSET + "*");
        cacheService.delete(listKey);
        cacheService.delete(zsetKey);
    }
}